<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clearList"
    />
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table doumee-element-tableb"
    >
      <el-table-column
        align="center"
        label="课程名称"
        min-width="120"
        prop="courseName"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="会员信息"
        min-width="180"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span class="name">{{ scope.row.memberName }}</span>
          <span v-if="scope.row.memberPhone" class="phone">-{{ scope.row.memberPhone }}</span>
          <span v-if="scope.row.memberCardId" class="phone">-{{ scope.row.memberCard }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="学员信息"
        min-width="120"
        prop="studentName"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="教练姓名"
        min-width="120"
        prop="teacherName"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="上课时间"
        min-width="160"
        prop="classDate"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="课程类型"
        prop="courseType"
        min-width="100"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.courseType=='4'">私教课</span>
          <span v-else>常规课</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="教练等级"
        prop="teacherLevelName"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="上课地点"
        prop="siteName"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="状态"
        prop="signIn"
        min-width="80"
        fixed="right"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.signIn=='1'">已签到</span>
          <span v-else>未签到</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        min-width="160"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="
                scope.row.signIn == 0 &&
                  meta.indexOf('StudentSignInPC') > -1
              "
              v-preventReClick
              type="text"
              @click="qdBtn(scope.row.id)"
            >签到</el-button>
            <el-button
              v-if="
                scope.row.signIn == '1' &&
                  meta.indexOf('StudentSignInPC') > -1
              "
              v-preventReClick
              type="text"
              @click="qdBtn(scope.row.id, '1')"
            >取消签到</el-button>
            <el-button
              v-if="
                meta.indexOf('ChangeCourseTimeStu') > -1
              "
              v-preventReClick
              type="text"
              @click="ghBtn(scope.row)"
            >更换课时</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />

    <el-drawer
      ref="drawerRef"
      title="换课"
      :visible.sync="isShowDrawer"
      :before-close="closeDrawer"
      size="900px"
    >
      <div class="drawer_wrap">
        <div class="header">
          <img class="img" :src="info.courseImageUrl">
          <div class="content">
            <div class="item">课程名称：{{ info.courseName }}</div>
            <div v-if="info.duration" class="item">课程时间：{{ info.duration }}分钟</div>
            <div class="item">教练姓名：{{ info.teacherName }}</div>
            <div v-if="info.price" class="item">课程价格：{{ info.price }}</div>
            <div v-if="info.courseType === '4'" class="item">课程模式：{{ info.classType == 1?'一对多': '一对一' }}</div>
            <div class="item">教练等级：{{ info.teacherLevelName }}</div>
            <div class="item">上课时间：{{ info.classDate }}</div>
            <div class="item">上课地点：{{ info.siteName }}</div>
          </div>
        </div>
        <el-form
          ref="drawerParam"
          class="doumee-form"
          :model="drawerParam"
          label-width="110px"
          label-suffix="："
          :rules="rules"
        >
          <div class="mb20 mt20">
            <span class="property-title">换课信息</span>
            <span class="placeholder9 ml20">注：换课仅更换课时信息，不补差价</span>
          </div>
          <template v-if="info.courseType !== '4'">
            <el-form-item label="课程名称">
              <el-input v-model="info.courseName" disabled class="w400" />
            </el-form-item>
            <el-form-item label="课时信息" prop="courseTimeId">
              <el-select v-model="drawerParam.courseTimeId" filterable placeholder="请选择课时信息" class="w400">
                <el-option
                  v-for="item in courseList"
                  :key="item.courseTimeId"
                  :label="item.day + ' (' + item.dayWeek + ') ' + item.startTime+ '~' + item.endTime"
                  :value="item.courseTimeId"
                />
              </el-select>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="课程日期" prop="day">
              <el-date-picker
                v-model="drawerParam.day"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                class="w400"
                placeholder="年-月-日"
                :picker-options="pickerOptions"
                @change="getreserveClassInfoPC"
              />
            </el-form-item>
            <el-form-item label="课程名称" prop="courseId" @change="getreserveClassInfoPC">
              <el-select v-model="drawerParam.courseId" filterable placeholder="请选择课程" class="w400">
                <el-option
                  v-for="item in kcList"
                  :key="item.courseId"
                  :label="item.courseName"
                  :value="item.courseId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="选择等级" prop="teacherLeavel">
              <el-radio-group v-model="drawerParam.teacherLeavel" @change="getTeachList">
                <el-radio
                  v-for="item in levelList"
                  :key="item.id"
                  :label="item.id"
                  :value="item.id"
                  class="mb5 mt5"
                >{{ item.levelName }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-show="drawerParam.teacherLeavel" label="教练" prop="teacherId">
              <el-select v-model="drawerParam.teacherId" clearable filterable placeholder="请选择教练" class="w400" @change="getreserveClassInfoPC">
                <el-option
                  v-for="item in teachList"
                  :key="item.teacherId"
                  :label="item.teacherName"
                  :value="item.teacherId"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-show="drawerParam.teacherLeavel && drawerParam.teacherId" label="可约时间段" prop="time">
              <el-select v-model="drawerParam.time" clearable filterable placeholder="请选择可约时间段" class="w400">
                <el-option
                  v-for="(item, index) in courseList"
                  :key="index"
                  :label="item.startTime+ '~' + item.endTime"
                  :value="index"
                />
              </el-select>
            </el-form-item>
          </template>
          <div class="property-title">其他信息</div>
          <el-form-item label="备注">
            <el-input v-model="drawerParam.remark" />
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="subLoading"
              type="primary"
              @click="onSubmit"
            >提交</el-button>
            <el-button
              @click="closeDrawer"
            >取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import { timeStuList, teacherLevelListPost, studentSignInPC, teacherList, canChangeCourseTimeStuList, changeCourseTimeStu, infoCourse, publishCourseList } from '@/api'
import { queryFormConfig } from './config'
import QueryForm from '@/components/QueryForm'
export default {
  name: 'OfflinecoursesRefund',
  components: {
    QueryForm
  },
  data() {
    return {
      queryFormConfig,
      teachList: [],
      meta: [],
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
        }
      },
      total: 0,
      filters: {},
      listLoading: true,
      info: {},
      isShowDrawer: false,
      drawerParam: {},
      courseList: [],
      subLoading: false,
      kcList: [],
      levelList: [],
      rules: {
        courseTimeId: [{ required: true, message: '请选择课时信息', trigger: 'change' }],
        day: [{ required: true, message: '请选择课程日期', trigger: 'change' }],
        courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
        teacherLeavel: [{ required: true, message: '请选择教练等级', trigger: 'change' }],
        teacherId: [{ required: true, message: '请选择教练', trigger: 'change' }],
        time: [{ required: true, message: '请选择可约时间', trigger: 'change' }]
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getCoachLevelList()
    this.getList(1)
  },
  methods: {
    getCoachLevelList() {
      teacherLevelListPost({ param: {}}).then(res => {
        const arr = res.recordList || []
        this.levelList = res.recordList || []
        this.queryFormConfig.formItems[5].options = arr
      })
    },
    // 课程列表
    getKcList() {
      const venueIds = [sessionStorage.getItem('venueId')]
      publishCourseList({ param: { venueIds, channel: '02', flag: '2' }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.kcList = res.recordList || []
        })
    },
    // 教练
    getTeachList() {
      const venueId = sessionStorage.getItem('venueId')
      teacherList({
        param: {
          venueId,
          levelId: this.drawerParam.teacherLeavel
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.teachList = res.recordList || []
          this.$set(this.drawerParam, 'teacherId', '')
          this.$set(this.drawerParam, 'time', '')
          this.$refs.drawerParam.clearValidate()
        })
        .catch(() => {})
    },
    // PC预约课程信息
    getreserveClassInfoPC() {
      const param = { ...this.drawerParam }
      if (!param.courseId || !param.teacherId || !param.day) {
        this.courseList = []
        return
      }
      canChangeCourseTimeStuList({ param: {
        courseId: param.courseId,
        courseType: '4',
        teacherId: param.teacherId,
        classDate: param.day
      }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.courseList = res.recordList || []
        this.$set(this.drawerParam, 'time', '')
        this.$refs.drawerParam.clearValidate()
      })
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    onSubmit() {
      const that = this
      const param = { ...this.drawerParam }
      this.$refs.drawerParam.validate((valid) => {
        if (valid) {
          if (param.courseType === '4') {
            param.startTime = that.courseList[param.time].startTime
            param.endTime = that.courseList[param.time].endTime
          }
          that.subLoading = true
          changeCourseTimeStu({ param }).then((res) => {
            that.subLoading = false
            if (res.errorCode !== '000000') return
            that.$message.success('换课成功')
            that.isShowDrawer = false
            that.getList()
          }).catch(() => { that.subLoading = false })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    ghBtn(e) {
      infoCourse({ param: { courseId: e.courseId }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.info = {
          ...e,
          classType: res.record.duration || '',
          duration: res.record.duration || '',
          pirce: res.record.pirce || '',
          courseImageUrl: res.record.courseImageUrl
        }
        if (e.courseType !== '4') {
          this.getCourseList(e.courseId)
          this.drawerParam = {
            courseType: e.courseType,
            courseId: e.courseId,
            oldTimeStuId: e.id
          }
        } else {
          this.getKcList()
          this.drawerParam = {
            courseType: e.courseType,
            courseId: e.courseId,
            oldTimeStuId: e.id,
            day: e.classDate.slice(0, 10)
          }
        }
        this.isShowDrawer = true
        this.$nextTick(() => {
          this.$refs.drawerParam.clearValidate()
        })
      })
    },
    getCourseList(courseId) {
      canChangeCourseTimeStuList({ param: { courseId }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.courseList = res.recordList || []
      })
    },
    qdBtn(id, val) {
      studentSignInPC({ param: { id, cancel: val || null }}).then((resb) => {
        if (resb.errorCode !== '000000') return
        const message = val ? '取消签到成功' : '签到成功'
        this.$message.success(message)
        this.getList()
      })
    },
    clearList() {
      this.filters = {}
      this.getList(1)
    },
    getList(page) {
      this.listLoading = true
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      timeStuList({ pagination, param: { venueId, ...filters }})
        .then(res => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.total = res.totalCount
            if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
              this.getList(Math.ceil(res.totalCount / pagination.rows))
            }
            this.$refs.table.doLayout()
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    closeDrawer() {
      this.isShowDrawer = false
    }
  }
}
</script>
<style lang="scss" scoped>
.drawer_wrap{
  .header{
    display: flex;
    .img{
      width: 140px;
      height: 70px;
      margin-right: 20px;
    }
    .content{
      display: flex;
      flex-wrap: wrap;
      .item{
        width: 33.33%;
        margin-bottom: 10px;
      }
    }
  }
}
</style>
